//
//  DJDrawView.swift
//  dj-learn-Swift
//
//  Created by Sun Jae on 2022/5/9.
//  Copyright © 2022 S.J. All rights reserved.
//

import UIKit

class DJDrawView: UIView {

    convenience init() {
        self.init(frame: .zero)
        self.backgroundColor = UIColor.gray
    }
    
    var paths: Array<UIBezierPath> = []
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        guard let point = touch?.location(in: touch?.view) else { return }
        let bezierPath = UIBezierPath()
        bezierPath.move(to: point)
        self.paths.append(bezierPath)
        self.setNeedsDisplay()
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        guard let point = touch?.location(in: touch?.view) else { return }
        let bezierPath: UIBezierPath = paths.last!
        bezierPath.addLine(to: point)
        self.setNeedsDisplay()
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        guard let point = touch?.location(in: touch?.view) else { return }
        let bezierPath: UIBezierPath = paths.last!
        bezierPath.addLine(to: point)
        self.setNeedsDisplay()
    }
    
    override func draw(_ rect: CGRect) {
        UIColor.black.set()
        for path in self.paths {
            path.lineWidth = 2.0
            path.lineJoinStyle = .round
            path.lineCapStyle = .round
            path.stroke()
        }
    }
}
